package com.gitee.loyo.act

import com.gitee.loyo.Helper
import com.gitee.loyo.KSQL
import com.gitee.loyo.interfaces.LazyReadMapper
import java.lang.reflect.Method
import java.lang.reflect.Proxy

interface Transferor{

    fun asLazyReadMapper(): LazyReadMapper

    fun insert(): Int

    fun create(): Any?

    fun update(): Int

    fun delete(): Int

}

interface TransferorFactory{

    fun transfer(model: Model<*, *>): Transferor

    fun invoke(cls: Class<*>, daoMethod: Method, args: Map<String, Any?>): Any?

}

object JDBCTransferorFactory: TransferorFactory{

    override fun transfer(model: Model<*, *>): Transferor = object: Transferor{

        override fun asLazyReadMapper()
        = KSQL.tryGetConnection().query(model.toSelectParameterizeSQL())

        override fun insert()
        = KSQL.tryGetConnection().update(model.toInsertParameterizeSQL())

        override fun create()
        = KSQL.tryGetConnection().insertForGeneratedKey(model.toInsertParameterizeSQL())

        override fun update(): Int
        = KSQL.tryGetConnection().update(model.toUpdateParameterizeSQL())

        override fun delete()
        = KSQL.tryGetConnection().update(model.toDeleteParameterizeSQL())

    }

    override fun invoke(cls: Class<*>, daoMethod: Method, args: Map<String, Any?>): Any? {
        return KSQL.tryGetConnection().invokeMapperFunction(daoMethod, args)
    }

}